package com.wangyonghao.harmonyocrs.slice;

import com.google.gson.Gson;
import com.wangyonghao.harmonyocrs.CameraAbility;
import com.wangyonghao.harmonyocrs.LoginAbility;
import com.wangyonghao.harmonyocrs.ResourceTable;
import com.wangyonghao.harmonyocrs.pojo.Result;
import com.wangyonghao.harmonyocrs.utils.OCRUtils;
import com.wangyonghao.harmonyocrs.utils.StringUtils;
import com.wangyonghao.harmonyocrs.utils.ToastUtils;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Image;
import ohos.agp.components.Text;
import ohos.agp.components.TextField;
import ohos.agp.components.surfaceprovider.SurfaceProvider;
import ohos.agp.window.service.WindowManager;
import ohos.media.image.ImagePacker;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.photokit.metadata.AVStorage;
import ohos.miscservices.pasteboard.PasteData;
import ohos.miscservices.pasteboard.SystemPasteboard;
import ohos.utils.net.Uri;

import java.io.*;

public class MainAbilitySlice extends AbilitySlice {
    Image logout;
    Image picture;
    Image camera;
    TextField result;
    Text gotoHistory;
    Text copy;

    int imgRequestCode = 1;
    int cameraRequestCode = 2;
    private SurfaceProvider surfaceProvider;
    Gson gson = new Gson();


    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        //设置切面全屏显示
        getWindow().addFlags(WindowManager.LayoutConfig.MARK_FULL_SCREEN |
                WindowManager.LayoutConfig.MARK_TRANSLUCENT_STATUS |
                WindowManager.LayoutConfig.MARK_TRANSLUCENT_NAVIGATION);
        initComponent();
        event();
        if (!StringUtils.isEmpty(intent.getStringParam("result"))) {
            Result res = gson.fromJson(intent.getStringParam("result"), Result.class);
            this.result.setText(res.getMessage());
        }
    }

    private void event() {
        logout.setClickedListener(e -> {
            Intent i = new Intent();
            Operation operation = new Intent.OperationBuilder()
                    .withDeviceId("")
                    .withBundleName(getBundleName())
                    .withAbilityName(LoginAbility.class.getName())
                    .build();
            i.setOperation(operation);
            startAbility(i);
        });
        picture.setClickedListener(e -> {
            selectPic();
        });
        camera.setClickedListener(e -> {
            Intent i = new Intent();
            Operation operation = new Intent.OperationBuilder()
                    .withDeviceId("")
                    .withBundleName(getBundleName())
                    .withAbilityName(CameraAbility.class.getName())
                    .build();
            i.setOperation(operation);
            startAbilityForResult(i, cameraRequestCode);
            terminateAbility();
        });
        gotoHistory.setClickedListener(e -> {
            Intent i = new Intent();
            present(new HistoryAbilitySlice(), i);
        });
        copy.setClickedListener(e -> {
            if (result.getText() == null || "".equals(result.getText())) {
                ToastUtils.showDialog(this, "暂无识别内容，请先识别~");
                return;
            }
            SystemPasteboard pasteboard = SystemPasteboard.getSystemPasteboard(getApplicationContext());
            if (pasteboard == null) {
                ToastUtils.showDialog(this, "获取粘贴板失败，请在设置中授予权限！");
            } else {
                pasteboard.setPasteData(PasteData.creatPlainTextData(result.getText().toString()));
                ToastUtils.showDialog(this, "已复制识别结果到粘贴板~");
            }
        });
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }


    private void initComponent() {
        logout = (Image) findComponentById(ResourceTable.Id_main_logout);
        picture = (Image) findComponentById(ResourceTable.Id_main_picture);
        camera = (Image) findComponentById(ResourceTable.Id_main_camera);
        result = (TextField) findComponentById(ResourceTable.Id_main_result);
        gotoHistory = (Text) findComponentById(ResourceTable.Id_main_goto_history);
        copy = (Text) findComponentById(ResourceTable.Id_main_copy_result);
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    private void selectPic() {
        Intent i = new Intent();
        Operation opt = new Intent.OperationBuilder().withAction("android.intent.action.GET_CONTENT").build();
        i.setOperation(opt);
        i.addFlags(Intent.FLAG_NOT_OHOS_COMPONENT);
        i.setType("image/*");
        startAbilityForResult(i, imgRequestCode);
    }

    @Override
    protected void onResult(int requestCode, Intent resultIntent) {
        super.onResult(requestCode, resultIntent);
        if (requestCode == cameraRequestCode) {

        }
    }

    protected void onAbilityResult(int requestCode, int resultCode, Intent resultData) {
        ToastUtils.showDialog(this, "返回了");
        result.setText("requestCode=" + requestCode + "\nresultCode=" + resultCode);
        if (requestCode == imgRequestCode) {
            //选择的Img对应的Uri
            String chooseImgUri = resultData.getUriString();
            //将字节数组读取为文件
            File file = byteToFile(chooseImgUri);
            if (file.length() < 10000000) {
                //识别图片内容
                try {
                    String s = OCRUtils.doOCR(file);
                    if (StringUtils.isEmpty(s)) {
                        ToastUtils.showDialog(this, "未识别到任何内容！");
                    } else {
                        Result resStr = gson.fromJson(s, Result.class);
                        result.setText(resStr.getMessage());
                    }
                } catch (Exception e) {
                    ToastUtils.showDialog(this, "图片识别失败！");
                    e.printStackTrace();
                }
            } else {
                ToastUtils.showDialog(this, "文件大小不能超过10M");
            }
        }
//        if (requestCode == cameraRequestCode) {
//            if (resultData == null) {
//                this.result.setText("未接受到任何带回的数据");
//                return;
//            }
//            Result res = gson.fromJson(resultData.getStringParam("result"), Result.class);
//            this.result.setText(res.getMessage());
//        }
    }

    public File byteToFile(String chooseImgUri) {
        File file = null;
        String subfix = "jpg";
//        result.setText(chooseImgUri);
////            ToastUtils.showDialog(this, chooseImgUri.substring(chooseImgUri.lastIndexOf(".")));
//        if (chooseImgUri.endsWith("jpg")) {
//            ToastUtils.showDialog(this, "jpg");
//        } else if (chooseImgUri.endsWith("png")) {
//            ToastUtils.showDialog(this, "png");
//            subfix = "png";
//        } else {
//            ToastUtils.showDialog(this, "图片格式错误，仅支持png或jpg！");
//            return;
//        }
        //定义数据能力帮助对象
        DataAbilityHelper helper = DataAbilityHelper.creator(getContext());
        //定义图片来源对象
        ImageSource imageSource = null;
        //获取选择的Img对应的Id
        String chooseImgId = null;
        //如果是选择文件则getUriString结果为content://com.android.providers.media.documents/document/image%3A30，其中%3A是":"的URL编码结果，后面的数字就是image对应的Id
        //如果选择的是图库则getUriString结果为content://media/external/images/media/30，最后就是image对应的Id
        //这里需要判断是选择了文件还是图库
        if (chooseImgUri.lastIndexOf("%3A") != -1) {
            chooseImgId = chooseImgUri.substring(chooseImgUri.lastIndexOf("%3A") + 3);
        } else {
            chooseImgId = chooseImgUri.substring(chooseImgUri.lastIndexOf('/') + 1);
        }
        //获取图片对应的uri，由于获取到的前缀是content，我们替换成对应的dataability前缀
        Uri uri = Uri.appendEncodedPathToUri(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI, chooseImgId);

        try {
            //读取图片
            FileDescriptor fd = helper.openFile(uri, "r");
            imageSource = ImageSource.create(fd, null);
            //创建位图
            PixelMap pixelMap = imageSource.createPixelmap(null);
            ImagePacker imagePacker = ImagePacker.create();
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ImagePacker.PackingOptions packingOptions = new ImagePacker.PackingOptions();
            imagePacker.initializePacking(byteArrayOutputStream, packingOptions);
            imagePacker.addImage(pixelMap);
            imagePacker.finalizePacking();
            byte[] bytes = byteArrayOutputStream.toByteArray();
//        ToastUtils.showDialog(this, "文件大小:" + bytes.length);
//        result.setText("文件大小:" + bytes.length);
//        result.setText(this.getCacheDir().getPath() + "/temp.png");
            try {
                // 根据绝对路径初始化文件
                file = new File(this.getCacheDir().getPath() + "/temp." + subfix);
                if (!file.exists()) {
                    file.createNewFile();
                }
                // 输出流
                OutputStream os = new FileOutputStream(file, false);
                os.write(bytes);
                os.close();
            } catch (Exception e) {
                e.printStackTrace();
                file = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (imageSource != null) {
                imageSource.release();
            }
        }
        return file;
    }
}
